
<script setup>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'

import { ref, watch } from 'vue'
// 提供数据
var arr = JSON.parse(localStorage.getItem('list')) || [
  {
    id: 1,
    name: '吃饭',
    done: true,
  },
  {
    id: 2,
    name: '睡觉',
    done: false,
  },
  {
    id: 3,
    name: '打豆豆',
    done: false,
  },
]
const list = ref(arr)

const changeStatus = (id) => {
  const objItem = list.value.find(item => item.id == id)
  objItem.done = !objItem.done
  // console.log(objItem);
}

/* 删除数据 */
const changeDel = (id) => {
  list.value = list.value.filter(item => item.id !== id)
}

/* 添加数据 */
const addHandle = (val) => {
  console.log(val);
  /* 
  push  shift  unshift  pop  sort reverse  splice
  */
  list.value.push({
    id: Date.now(),
    name: val,
    done: true,
  })
}

/* 实现反选 */
const chkA = (flag) => {
  // 将数组中的每一项设置成flag值
  list.value.forEach(item => {
    item.done = flag
  })
}

/* 监听数据持久化 */
watch(list, (newVal) => {
  console.log(newVal, 9999);
  localStorage.setItem('list', JSON.stringify(list.value))

}, {
  deep: true
})
</script>

<template>
  <section class="todoapp">
    <TodoHeader :list="list" @addHandle="addHandle"></TodoHeader>
    <TodoMain @chkA="chkA" :list="list" @changeStatus="changeStatus" @changeDel="changeDel"></TodoMain>
    <TodoFooter :list="list"></TodoFooter>
  </section>
</template>

<style>
</style>
